const fs = require('fs')
const resolve = require('path').resolve
const ejs = require('ejs')

function rendTemplate(src, dest, data) {
    fs.readdir(src, (err, paths) => {
        if (err) throw err
        paths.forEach(path => {
            const _src = src + '/' + path
            const _dest = dest + '/' + path
            let read, write
            fs.stat(_src, (err, st) => {
                if (err) throw err
                if (st.isFile()) {
                    ejs.renderFile(_src, data, (err, result) => {
                        if(err) throw err
                        fs.writeFileSync(_dest, result, 'utf-8')
                    })
                } else if (st.isDirectory()) {
                    exists(_src, _dest, data, rendTemplate)
                }
            })
        })
    })
}

function exists(src,dest, data, callback) {
    if(fs.existsSync(dest)){
        callback(src, dest, data)
    }else{
        fs.mkdir(dest, () => {
            callback(src, dest, data)
        })
    }
}

module.exports = { rendTemplate }
